<?php

/**
 *   OPENSHOP 管理中心花名册批量上传、修改
 * 
 *   @link        http://baison.com.cn
 *   @copyright   Baison, Inc.
 *   @package     OpenShop
 *   @version     $Id: roster_batch.php,v 1.0 2009/06/17 08:36:58 modified $
 *   @author      FillBag <fillbag@hotmail.com>
 */

define('IN_OS', true);

require(dirname(__FILE__) . '/includes/init.php');

/*------------------------------------------------------ */
//-- 批量上传
/*------------------------------------------------------ */
$upload_roster['consignee'] = '客户姓名';
$upload_roster['sex'] = '性别';
$upload_roster['birthday'] = '生日';   // 需要转换成brand_id
$upload_roster['email'] = '邮件地址';
$upload_roster['mobile'] = '手机';
$upload_roster['office_phone'] = '办公电话';
$upload_roster['home_phone'] = '家庭电话';
$upload_roster['country'] = '国家';
$upload_roster['province'] = '省份';
$upload_roster['city'] = '城市';
$upload_roster['district'] = '地区';
$upload_roster['address'] = '详细地址';
$upload_roster['zipcode'] = '邮编';
$upload_roster['sign_building'] = '标志建筑';
$upload_roster['best_time'] = '最佳送货时间';
	
if ($_REQUEST['act'] == 'add')
{
    /* 检查权限 */
    admin_priv();

    /* 取得可选语言 */
    $dir = opendir(SOURCE_PATH . 'languages');
    $lang_list = array(
        'UTF8'      => $_LANG['charset']['utf8'],
        'GB2312'    => $_LANG['charset']['zh_cn'],
        'BIG5'      => $_LANG['charset']['zh_tw'],
    );
    $download_list = array();
    while (@$file = readdir($dir))
    {
        if ($file != '.' && $file != '..' && $file != ".svn" && $file != "_svn" && is_dir(SOURCE_PATH . 'languages/' .$file) == true)
        {
            $download_list[$file] = sprintf('下载批量CSV文件（%s）', isset($_LANG['charset'][$file]) ? $_LANG['charset'][$file] : $file);
        }
    }
    @closedir($dir);
    $smarty->assign('lang_list',     $lang_list);
    $smarty->assign('download_list', $download_list);

    /* 参数赋值 */
    $smarty->assign('ur_here', '目录花名册批量上传');

    /* 显示模板 */
    assign_query_info();
	
	$smarty->display('roster_batch_add.tpl');
}
elseif ($_REQUEST['act'] == 'upload')
{
    /* 检查权限 */
    admin_priv('add_roster_batch');

    /* 将文件按行读入数组，逐行进行解析 */
    $line_number = 0;
    $roster_list = array();
    $field_list = array_keys($upload_roster); // 字段列表
    $data = file($_FILES['file']['tmp_name']);
    foreach ($data AS $line)
    {
        // 跳过第一行
        if ($line_number == 0)
        {
            $line_number++;
            continue;
        }

        // 转换编码
        if (($_POST['charset'] != 'UTF8') && (strpos(strtolower(OS_CHARSET), 'utf') === 0))
        {
            $line = os_iconv($_POST['charset'], 'UTF8', $line);
        }

        // 初始化
        $arr    = array();
        $buff   = '';
        $quote  = 0;
        $len    = strlen($line);
        for ($i = 0; $i < $len; $i++)
        {
            $char = $line[$i];

            if ('\\' == $char)
            {
                $i++;
                $char = $line[$i];

                switch ($char)
                {
                    case '"':
                        $buff .= '"';
                        break;
                    case '\'':
                        $buff .= '\'';
                        break;
                    case ',';
                        $buff .= ',';
                        break;
                    default:
                        $buff .= '\\' . $char;
                        break;
                }
            }
            elseif ('"' == $char)
            {
                if (0 == $quote)
                {
                    $quote++;
                }
                else
                {
                    $quote = 0;
                }
            }
            elseif (',' == $char)
            {
                if (0 == $quote)
                {
                    if (!isset($field_list[count($arr)]))
                    {
                        continue;
                    }
                    $field_name = $field_list[count($arr)];
                    $arr[$field_name] = trim($buff);
                    $buff = '';
                    $quote = 0;
                }
                else
                {
                    $buff .= $char;
                }
            }
            else
            {
                $buff .= $char;
            }

            if ($i == $len - 1)
            {
                if (!isset($field_list[count($arr)]))
                {
                    continue;
                }
                $field_name = $field_list[count($arr)];
                $arr[$field_name] = trim($buff);
            }
        }
        $roster_list[] = $arr;
    }
    
    //取得国家列表，如果有收货人列表，取得省市区列表
    foreach ($roster_list AS $region_id => $roster)
    {
    	$country_id = $db->getOne("SELECT region_id FROM ".$os->table('region')." WHERE parent_id=0 AND region_type=0 AND region_name LIKE '%".$roster['country']."%'");
    	$province_id = $db->getOne("SELECT region_id FROM ".$os->table('region')." WHERE parent_id='$country_id' AND region_type=1 AND region_name LIKE '%".$roster['province']."%'");
    	$city_id = $db->getOne("SELECT region_id FROM ".$os->table('region')." WHERE parent_id='$province_id' AND region_type=2 AND region_name LIKE '%".$roster['city']."%'");
    	$district_id = $db->getOne("SELECT region_id FROM ".$os->table('region')." WHERE parent_id='$city_id' AND region_type=3 AND  region_name LIKE '%".$roster['district']."%'");
    	    	
        $roster['country']  = isset($country_id)  ? intval($country_id)  : 0;
        $roster['province'] = isset($province_id) ? intval($province_id) : 0;
        $roster['city']     = isset($city_id)     ? intval($city_id)     : 0;
        $roster['district'] = isset($district_id)     ? intval($district_id)     : 0;
        
        $roster_l[] = $roster;
        $province_list[$region_id] = get_regions(1, $roster['country']);
        $city_list[$region_id]     = get_regions(2, $roster['province']);
        $district_list[$region_id] = get_regions(3, $roster['city']);
    }
    
    $smarty->assign('roster_list', $roster_l);

    // 字段名称列表
    $smarty->assign('title_list', $upload_roster);
    
    $smarty->assign('country_list',       get_regions());
    
    $smarty->assign('province_list',    $province_list);
    $smarty->assign('city_list',        $city_list);
    $smarty->assign('district_list',    $district_list);
        
    // 显示的字段列表
    $smarty->assign('field_show', array('consignee' => true, 'email' => true , 'office_phone' => true, 'home_phone' => true, 'address' => true));
    $smarty->assign('name_of_region',   array($_CFG['name_of_region_1'], $_CFG['name_of_region_2'], $_CFG['name_of_region_3'], $_CFG['name_of_region_4']));

    /* 参数赋值 */
    $smarty->assign('ur_here', '批量上传确认');

    /* 显示模板 */
    assign_query_info();
	
	$smarty->display('roster_batch_confirm.tpl');
	
}elseif ($_REQUEST['act'] == 'insert')
{
    /* 检查权限 */
    admin_priv('add_roster_batch');

    if (isset($_POST['checked']))
    {
        /* 字段默认值 */
        $default_value = array(
            'roster_id'     => 0,
            'consignee'     => '',
            'sex'           => 0,
            'birthday'      => '0000-00-00',
            'email'         => '',
            'reg_time'      => 0,
            'office_phone'  => '',
            'home_phone'    => '',
            'country'       => 0,
            'province'      => 0,
            'city'          => 0,
            'district'      => 0,
            'address'       => '',
            'zipcode'       => '',
            'mobile'        => '',
            'sign_building' => '',
            'best_time'     => ''           
        );

        /* 字段列表 */
        $field_list = array_keys($upload_roster);


        /* 循环插入商品数据 */
        foreach ($_POST['checked'] AS $key => $value)
        {
            // 合并
            $field_arr = array(
                'reg_time'      => gmtime()
            );

            foreach ($field_list AS $field)
            {
                // 转换编码
                $field_value = isset($_POST[$field][$value]) ? $_POST[$field][$value] : '';

                // 如果字段值为空，且有默认值，取默认值
                $field_arr[$field] = !isset($field_value) && isset($default_value[$field]) ? $default_value[$field] : $field_value;
            }

            $db->autoExecute($os->table('roster'), $field_arr, 'INSERT');

            $max_id = $db->insert_id() + 1;
        }
    }

    // 记录日志
    admin_log('', 'batch_upload', 'roster');

    /* 显示提示信息，返回商品列表 */
    $link[] = array('href' => 'roster.php?act=list', 'text' => '返回目录花名册列表');
    sys_msg('批量上传成功', 0, $link);
    
}elseif ($_REQUEST['act'] == 'download'){
	
    // 文件标签
    // Header("Content-type: application/octet-stream");
    header("Content-type: application/vnd.ms-excel; charset=utf-8");
    Header("Content-Disposition: attachment; filename=roster_list.csv");

    /* 创建字符集转换对象 */
    if ($_GET['charset'] == 'zh_cn' || $_GET['charset'] == 'zh_tw')
    {
        $to_charset = $_GET['charset'] == 'zh_cn' ? 'GB2312' : 'BIG5';
        echo os_iconv(OS_CHARSET, $to_charset, join(',', $upload_roster));
    }
    else
    {
        echo join(',', $upload_roster);
    }

}
?>